package leetcode.code1530;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.tree.TreeNode;

public class Solution implements IDebug {


	int ans;
	int distance;

	public int countPairs(TreeNode root, int distance) {
		this.ans = 0;
		this.distance = distance;
		this.f(root, 1);
		return ans;
	}

	private List<Integer> f(TreeNode root, int high) {
		if (root == null) {
			return null;
		}
		if (root.left == null && root.right == null) {
			return Arrays.asList(high);
		}
		List<Integer> left = null;
		if (root.left != null) {
			left = this.f(root.left, high + 1);
		}
		List<Integer> right = null;
		if (root.right != null) {
			right = this.f(root.right, high + 1);
		}

		if (left != null && right != null) {
			for (Integer l : left) {
				for (Integer element : right) {
					if (l - high + element - high <= this.distance) {
						this.ans += 1;
					}
				}
			}
		}
		List<Integer> result = new ArrayList<>();
		if (left != null) {
			result.addAll(new ArrayList<>(left));
		}
		if (right != null) {
			result.addAll(new ArrayList<>(right));
		}
		return result;
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
